const express = require('express')
const app = express()
// 导入WebSocket模块:
const WebSocket = require('ws');
// 引用Server类:
const WebSocketServer = WebSocket.Server;
// 实例化:
const wss = new WebSocketServer({
	port: 8085
});
//设置允许跨域访问该服务 
const AllowOrigin = require('./Access-Control-Allow-Origin.js')
AllowOrigin(app)
// 连接数据库
const db = require('./connection.js')
//引入SQL语句
const sql = require('./sql.js')
//存储连接用户
let userList = [] 
//存储在线人数 
let onLine = 0 

//test mysql start
// db.query(sql.user.queryById,[id],(err,res)=>{
// 	if(err){
// 		console.log(err,'查询失败');
// 		return
// 	}
// 	console.log(res,'查询成功！');
// 	})


// test mysql ending

wss.on('connection', function(ws, req) {
	// 记录当前人数
	onLine = wss._server._connections
	console.log('当前在线人数---', onLine);
	console.log(req.url, 'url');
	// 获取当前用户请求的url
	let url = req.url
	let reg = /[1-9][0-9]*/g //正则->截取数字
	let senderID = url.match(reg)[0]
	let acceptorID = url.match(reg)[1]
	console.log(senderID,'senderID');
	// 存储在线用户队列
	db.query(sql.user.queryById,[senderID],(err,res)=>{
		if(err){
			console.log(err,'查询发生了错误！');
			return
		}
		console.log(senderID, 'senderID');
		console.log(acceptorID, 'acceptorID');
		console.log('connect url one is ', req.url);
		ws.send('service tips:welcome to the homeland !')
		// console.log(res,'查询结果！');
		userList.map(item=>{
			if(item.uid == senderID){
				console.log('当前用户在线状态已存储！');
				return
			}else{
				let temp = res[0].ws = ws
				userList.push(res[0])
				console.log(userList);
			}
		})
	})
	if (senderID) {
		userList.map(item => {
			if (item.id === senderID) {
				console.log('welcome ' + item.name + ' to our homeland~');
			}
		})
	}
	// test start
	if (senderID == 1 && acceptorID == 3) {
		ws.send('1 send 3')
	}
	// test end
	ws.on('message', function(message) {
		console.log(message, '当前收到的消息');
		let MESS = JSON.parse(message)
		MESS.ws = ws
		user.push(MESS)
		if (MESS.id == 1) {
			console.log('user[2]');
			user[1].ws.send('21231231')
		}
		// 存储消息队列
		// db.query(sql.chat.insert,)
		// console.log(user,'userList');
		user.map(item => {
			if (item.id == 3) {
				console.log('给当前用户：3 发了消息');
				item.ws.send('15123132')
			}
		})
		console.log('发送了：--------------');
		// user[2]['ws'].send('1231231');
		// console.log(user[],'当前数组的的的的额');

		//广播 
		// wss.clients.forEach(function each(client) {
		// 	if (client !== ws && client.readyState === WebSocket.OPEN) {
		// 		client.send(message);
		// 	}
		// });
	})
	// 监听用户关闭
	ws.on('close', (code, reason) => {
		// ws.send('服务器关闭与您的链接')
		console.log(reason, 'reson');
		user.map(item => {
			if (item.id == Number(reason)) {
				console.log(item);
			}
		})
		console.log(code);
		console.log(reason + '==========' + typeof reason)
	})
});
wss.broadcast = function broadcast(data) {
	wss.clients.forEach(function each(client) {
		if (client.readyState === WebSocket.OPEN) {
			client.send(data);
		}
	});
};
// ws.on('pong', () => { console.log('server: received pong from client'); })//ws是通过ping/pong 心跳维护连接的

wss.clients.forEach(function(item) { //广播
	if (item._ultron.id == ws._ultron.id) {
		return
	}
	// console.log(item._ultron) 
	item.send(JSON.stringify(arr))
})
// 监听用户退出

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(3001, () => console.log('listening on port 3000!'))
